package com.swinw.asumall.cart.controller;

import com.swinw.asumall.cart.interceptor.CartInterceptor;
import com.swinw.asumall.cart.service.CartService;
import com.swinw.asumall.cart.vo.Cart;
import com.swinw.asumall.cart.vo.CartItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.concurrent.ExecutionException;

@Controller
public class CartController {

    @Autowired
    CartService cartService;

    /**
     * 获取用户所有选中的购物项信息
     * @return
     */
    @ResponseBody
    @GetMapping("/getCartItems")
    public List<CartItem> getCartItems(){
        return cartService.getCartItems();
    }


    @GetMapping("/checkItem")
    public String checkItem(Long skuId, Boolean check){
        cartService.checkItem(skuId,check);
        return "redirect:http://cart.swinw.com/cartList.html";
    }

    @GetMapping("/countItem")
    public String countItem(Long skuId, Integer itemCount){
        cartService.countItem(skuId,itemCount);
        return "redirect:http://cart.swinw.com/cartList.html";
    }

    @GetMapping("/deleteItem")
    public String deleteItem(Long skuId){
        cartService.deleteItem(skuId);
        return "redirect:http://cart.swinw.com/cartList.html";
    }

    @GetMapping("/cartList.html")
    public String cartList(Model model){
        Cart cartItems= cartService.getCartItem();
        model.addAttribute("cart",cartItems);
        model.addAttribute("pp",cartItems.getTotalAmount());
        return "cartList";
    }

    /**
     * 加入购物车
     * @param skuId 商品ID
     * @param num 商品数量
     * @return
     */
    @GetMapping("/addToCart")
    public String success(@RequestParam("skuId") Long skuId,
                          @RequestParam("num") Integer num,
                          Model model) throws ExecutionException, InterruptedException {
        CartItem item = cartService.addToCart(skuId,num);

        model.addAttribute("item",item);
        return "success";
    }

}
